package bot

import (
	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
	"lidongyooo/search-bot/models"
	"lidongyooo/search-bot/pkg/config"
	"lidongyooo/search-bot/pkg/db"
	"log"
	"strconv"
	"strings"
)

type MyMessage struct {
	*tgbotapi.Message
}

func GetMessageTableName(id int) string {
	return "chats_messages_" + strconv.Itoa(id%config.Viper.GetInt("MESSAGE.MODULO"))
}

func (ms *MyMessage) Search(keyword string) {
	originChatId := models.GetOriginChatId(int(ms.Chat.ID))
	tableName := GetMessageTableName(originChatId)

	var count int64
	db.MySQL.Table(tableName).Where("chat_id", originChatId).Count(&count)
	if count > config.Viper.GetInt64("MESSAGE.COUNT") {
		db.MySQL.Table(tableName).Where("chat_id", originChatId).Limit(int(count - config.Viper.GetInt64("MESSAGE.COUNT"))).Delete(&models.Message{})
	}

	var messages []models.Message
	res := db.MySQL.Raw("SELECT * FROM "+tableName+" WHERE chat_id = ? AND MATCH(text) AGAINST(?) ORDER BY id DESC LIMIT ?", originChatId, keyword, config.Viper.GetInt("MESSAGE.LIMIT")).Scan(&messages)

	if res.RowsAffected > 0 {
		var messageIds []string
		for _, message := range messages {
			messageIds = append(messageIds, strconv.Itoa(int(message.Id)))
		}

		searchModel := models.Search{
			ChatId:       originChatId,
			ChatName:     ms.Chat.Title,
			MessageTable: tableName,
			MessageIds:   strings.Join(messageIds, ","),
		}
		db.MySQL.Create(&searchModel)

		entities := []tgbotapi.MessageEntity{
			tgbotapi.MessageEntity{
				Type:   "text_link",
				Length: 7,
				Offset: 0,
				URL:    "http://" + config.Viper.GetString("DOMAIN") + "/search/" + strconv.Itoa(int(searchModel.Id)),
			},
			tgbotapi.MessageEntity{
				Type:   "text_link",
				Length: 3,
				Offset: 12,
				URL:    "https://t.me/" + Me.UserName,
			},
		}

		msg := tgbotapi.MessageConfig{
			BaseChat: tgbotapi.BaseChat{
				ChatID:           ms.Chat.ID,
				ReplyToMessageID: ms.MessageID,
			},
			Text:                  "查询结果已生成，本服务由@Me提供",
			Entities:              entities,
			DisableWebPagePreview: false,
		}
		_, err := Bot.Send(msg)
		if err != nil {
			log.Println(err)
		}
	} else {
		Bot.SendReplyMessage(ms.Chat.ID, ms.MessageID, "未找到相关消息")
	}
}
